package per.srp.demo.carLink;

import per.srp.demo.carLink.entity.Car;
import per.srp.demo.carLink.entity.CarAndSocket;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class CarDataManager {
    private static boolean updataData = false;

    private static Map<String, CarAndSocket> carInfo = new HashMap<>();

    private static void updata(){
        Iterator<Map.Entry<String,CarAndSocket>> it = carInfo.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String,CarAndSocket> entry = it.next();
            if(entry.getValue().getSocket().isClosed())
                it.remove();//使用迭代器的remove()方法删除元素
        }
    }

    //插入数据
    synchronized static public CarAndSocket insert(CarAndSocket carAndSocket){
        return carInfo.put(carAndSocket.getCar().getNo(),carAndSocket);
    }

    //读取所有数据
    public static  ArrayList<Car> queryAll(){
        //更新车辆信息
        if(updataData){
            updata();
        }

        ArrayList<Car> cars = new ArrayList<>();
        for (CarAndSocket carAndSocket  : carInfo.values()){
            try {
                cars.add((Car)carAndSocket.getCar().clone());
            } catch (CloneNotSupportedException e) {
                cars.add(null);
            }
        }

        return cars;
    }
}
